<template>
  <div class="Users">
    <el-breadcrumb separator="/" class="home">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <template>
        <el-input
          placeholder="请输入内容"
          class="input-with-select"
          v-model="query"
          @change="onSearch"
        >
          <el-button slot="append" icon="el-icon-search" @click="onSearch"></el-button>
        </el-input>
        <el-button type="primary" class="btn" @click="goAddVisible">添加用户</el-button>
      </template>
      <template>
        <el-table border style="width: 100%;" :data="users">
          <el-table-column type="index" label="#"> </el-table-column>
          <el-table-column label="姓名" prop="username"></el-table-column>
          <el-table-column label="邮箱" prop="email"></el-table-column>
          <el-table-column label="电话" prop="mobile"></el-table-column>
          <el-table-column label="角色" prop="role_name"></el-table-column>
          <el-table-column label="状态" prop="mg_state">
            <template #default="{ row }">
              <el-switch
                active-color="#13ce66"
                inactive-color="#dddddd"
                v-model="row.mg_state"
                @change="userState(row.id, $event)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <!-- 修改按钮 -->
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="goGetVisible(scope.row.id)"
              >
              </el-button>
              <!-- 删除按钮 -->
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="delVisible(scope.row.id)"
              ></el-button>
              <!-- 分配角色 -->
              <el-tooltip :enterable="false" effect="dark" content="分配角色" placement="top-start">
                <el-button size="mini" type="warning" icon="el-icon-s-tools"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template>
        <div class="block">
          <el-pagination
            @current-change="onCurrentChange"
            @size-change="onSizeChange"
            :current-page="current"
            :page-sizes="[1, 2, 5, 10, 50, 100]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            class="pagination"
          >
          </el-pagination>
        </div>
      </template>
    </el-card>
    <!-- 添加用户模块 -->
    <el-dialog title="添加用户" :visible.sync="addVisible.visible" width="50%">
      <el-form ref="ruleForm" label-width="80px" :rules="rules" :model="ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model.trim="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model.trim="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model.trim="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model.trim="ruleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addVisible.visible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户模块 -->
    <el-dialog title="编辑用户" :visible.sync="putVisible.visible" width="50%">
      <el-form ref="putFormRef" label-width="80px" :rules="putFormRules" :model="getForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="getForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="getForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="getForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="putVisible.visible = false">取 消</el-button>
        <el-button type="primary" @click="putUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ruleForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      getForm: {
        id: '',
        username: '',
        email: '',
        mobile: '',
      },
      addVisible: {
        visible: false,
      },
      putVisible: {
        visible: false,
      },
      // 查询参数
      query: '',
      // 当前页码
      pagenum: 1,
      current: 1,
      // 每页显示多少条
      pagesize: 5,
      // 总共多少条
      total: 0,
      // 把数据放到空数组里面
      users: [],
      putFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
            message: '格式不正确',
            trigger: 'blur',
          },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            pattern: /^1[356789]\d{9}$/,
            message: '格式不正确',
            trigger: 'blur',
          },
        ],
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 12, message: '长度在 2 到 12 个字符', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
            message: '格式不正确',
            trigger: 'blur',
          },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            pattern: /^1[356789]\d{9}$/,
            message: '格式不正确',
            trigger: 'blur',
          },
        ],
      },
    };
  },

  methods: {
    delVisible(id) {
      this.$confirm('是否删除该用户？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.request.del(id).then((res) => {
            if (res.data.meta.status === 200) {
              this.$message.success('删除成功');
              this.getUsers();
            } else {
              this.$message.error(res.data.meta.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          });
        });
    },
    userState(id, state) {
      this.request.userState(id, state).then((res) => {
        // console.log(res);
        if (res.data.meta.status === 200) {
          return this.$message.success('状态修改成功');
        }
        this.$message.error('状态修改失败');
      });
    },
    addUser() {
      this.$refs.ruleForm
        .validate()
        .then(() => {
          return this.request.add(this.ruleForm);
        })
        .then((res) => {
          if (res.data.meta.status === 201) {
            this.$message.success('用户添加成功');
            this.addVisible.visible = false;
            // 重置表单的操作
            this.$refs.ruleForm.resetFields();
            this.getUsers();
          } else {
            this.$message.error('用户添加失败');
          }
        });
    },
    putUser() {
      this.$refs.putFormRef.validate().then(() => {
        this.request.put(this.getForm.id, this.getForm.email, this.getForm.mobile).then((res) => {
          // console.log(res);
          if (res.data.meta.status === 200) {
            this.$message.success('用户信息修改成功');
            // console.log(res);
            this.putVisible.visible = false;
            this.getUsers();
          } else {
            this.$message.error('用户信息修改失败');
          }
        });
      });
    },
    goGetVisible(id) {
      // console.log(id);
      this.request.get(id).then((res) => {
        if (res.data.meta.status === 200) {
          // console.log(res);
          this.getForm = res.data.data;
        } else {
          this.$message.error('用户信息获取错误');
        }
      });
      this.putVisible.visible = true;
    },
    goAddVisible() {
      this.addVisible.visible = true;
    },
    onSearch() {
      // this.current = 1;
      this.getUsers();
    },
    onCurrentChange(current) {
      this.pagenum = current;
      this.current = current;
      this.getUsers();
    },
    onSizeChange(size) {
      this.pagesize = size;
      this.getUsers();
    },
    getUsers() {
      this.request
        .getUsers({
          query: this.query,
          current: this.current,
          pagenum: this.pagenum,
          pagesize: this.pagesize,
          total: this.total,
        })
        .then((res) => {
          // console.log(res);
          if (res.data.meta.status === 200) {
            this.total = res.data.data.total;
            this.users = res.data.data.users;
          }
        });
    },
  },
  created() {
    this.getUsers();
  },
};
</script>

<style lang="less" scoped>
.Users {
  .home {
    font-size: 12px;
  }
  .box-card {
    margin-top: 20px;
    .input-with-select {
      width: 400px;
      margin-bottom: 20px;
    }
    .btn {
      margin-left: 20px;
    }
    .pagination {
      margin-top: 15px;
    }
  }
}
</style>
